package cn.edu.shu.wechat.core.menu;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import cn.edu.shu.wechat.core.http.HttpsUtil;
import cn.edu.shu.wechat.core.token.MyToken;
import cn.edu.shu.wechat.core.util.MessageUtil;

public class MenuManager {
	private static Logger logger = Logger.getLogger(MenuManager.class);

	private static final String MENU_CREATE_POST_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
	private static final String MENU_GET_GET_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";
	private static final String MENU_DEL_GET_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=";
	private MyToken myToken;
	private String accessToken;

	public MenuManager() {
	}

	private void init(){
		this.accessToken = this.myToken.getToken();
		logger.info("get token from memeory ... token:"+this.accessToken);
	}
	/**
	 * 创建菜单
	 * 
	 * @throws WeChatException
	 */
	public void create(Menu menu) {
		init();
		String json=null;
		ObjectMapper mapper = new ObjectMapper();
	    try {
			 json = mapper.writeValueAsString(menu);
		} catch (IOException e) {
			logger.error("convert java object to json error! e:"+e);
		}
		if (MessageUtil.isSuccess(
				HttpsUtil.sendPostRequest(MENU_CREATE_POST_URL + this.accessToken,json))) {
			logger.info("create menu success !");
		} else {
			logger.info("create menu error !");
		}
	}

	/**
	 * 查询菜单
	 */
	public Menu getMenu() {
		init();
		logger.info("query the menu..");
		JsonObject jsonObject = HttpsUtil.sendGetRequest(MENU_GET_GET_URL + this.accessToken);
		Gson gson = new Gson();
		return gson.fromJson(jsonObject, Menu.class);
	}

	/**
	 * 删除菜单
	 * 
	 * @throws WeChatException
	 */
	public void delete() {
		init();
		JsonObject jsonObject = HttpsUtil.sendGetRequest(MENU_DEL_GET_URL + this.accessToken);
		if (MessageUtil.isSuccess(jsonObject)){
			logger.info("delete menu success !");
		}
		else{
			logger.info("detele menu error !");
		}
	}

	
	public void setMyToken(MyToken myToken) {
		this.myToken = myToken;
	}
	
	

}
